﻿using Microsoft.Phone.Controls;
using System.Linq;
using TombstoneHelper;
using System.Windows.Navigation;

namespace WaitLess.App.Views
{
    public class PhoneApplicationPageBase : PhoneApplicationPage
    {
        /// <summary>
        /// Ensure that every object you want to be preserved has a Name specified.
        /// To improve performance, you can specifiy which controls, e.g. this.SaveState(typeof(ScrollViewer));
        /// </summary>
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            this.SaveState(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            RemoveFoursquareAuthenticationStepFromNavigationStack(e);

            this.RestoreState();
        }

        /// <summary>
        /// To avoid user going back to authentication step
        /// </summary>
        private void RemoveFoursquareAuthenticationStepFromNavigationStack(NavigationEventArgs e)
        {
            if(!NavigationService.BackStack.Any())
                return;

            var previousPageIsFoursquareAuth = (NavigationService.BackStack.Last().Source.ToString().Contains("FoursquarePage.xaml"));
            if (previousPageIsFoursquareAuth)
                NavigationService.RemoveBackEntry();
        }
    }
}
